import 'package:app_installer/app_installer.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart' hide SimpleDialog;
import 'package:hotpot/route/route_ext.dart';
import 'package:hotpot/route/route_mixin.dart';
import 'package:hotpot/route/routes.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class DownloadPage extends StatefulWidget {
  const DownloadPage({super.key});

  @override
  State<DownloadPage> createState() => _DownloadPageState();
}

class _DownloadPageState extends State<DownloadPage> with ArgMixin {
  late final String url;

  var canDownload = false;
  var progress = 0.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkPermission();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (canDownload) downloadWidget() else checkWidget(),
        ],
      ),
    );
  }

  @override
  void loadArg(Map<String, dynamic> arg) {
    // TODO: implement loadArg
    url = arg['url'];
  }

  void checkPermission() async {
    var info = await DeviceInfoPlugin().androidInfo;
    bool can;
    if (info.version.sdkInt >= 33) {
      can = (await Permission.photos.request()).isGranted;
    } else if (info.version.sdkInt >= 29) {
      can = (await Permission.manageExternalStorage.request()).isGranted;
    } else {
      can = (await Permission.storage.request()).isGranted;
    }
    if (can) {
      canDownload = true;
      download();
      setState(() {});
    } else {
      Routes.splash.pushNamedAndPopAll();
    }
  }

  downloadWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        LinearProgressIndicator(value: progress / 100),
        20.hSizedBox,
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            'Downloading...'.text(size: 16, color: Colors.black),
            '${progress.toStringAsFixed(2)}%'.text(size: 16, color: Colors.black),
          ],
        ),
      ],
    ).sizedBox(width: 250).alignCenter();
  }

  checkWidget() {
    return 'Checking permissions.'.text(size: 16, color: Colors.black).alignCenter();
  }

  void download() async {
    // 使用 Dio 下载文件
    Dio dio = Dio();
    String savePath = '${(await getApplicationCacheDirectory()).path}/app-release.apk';
    print(savePath);
    print(url);
    var result = await dio.download(
      url,
      savePath,
      onReceiveProgress: (received, total) {
        progress = received / total * 100;
        print("下载进度: $progress%, $received, $total");
        setState(() {});
      },
      options: Options(
        responseType: ResponseType.bytes,
        receiveTimeout: const Duration(minutes: 30),
      ),
    );
    if (result.statusCode == 200) {
      AppInstaller.installApk(savePath);
    } else {
      Routes.splash.pushNamedAndPopAll();
    }
  }
}
